package com.laxcen.basiclib.utils;

import android.util.Log;

import com.laxcen.basiclib.BaseConst;


/**
 *  打印日志
 */
public class LogUtil {

    private static final String LOG_FORMAT = "%1$s\n%2$s";
    private static boolean isDebug = BaseConst.DEBUG;
    public static void d(String tag, Object... args) {
        log(Log.DEBUG, null, tag, args);
    }
    public static void i(String tag, Object... args) {
        log(Log.INFO, null, tag, args);
    }

    public static void w(String tag, Object... args) {
        log(Log.WARN, null, tag, args);
    }

    public static void e(Throwable ex) {
        log(Log.ERROR, ex, null);
    }

    public static void e(String tag, Object... args) {
        log(Log.ERROR, null, tag, args);
    }

    public static void e(Throwable ex, String tag, Object... args) {
        log(Log.ERROR, ex, tag, args);
    }

    private static void log(int priority, Throwable ex, String tag, Object... args) {
        if (isDebug == false) return;
        String log = "";
        if (ex == null) {
            if (args != null && args.length > 0) {
                for (Object obj : args) {
                    log += String.valueOf(obj)+",";
                }
                int segmentSize = 3 * 1024;
                long length = log.length();
                if (length <= segmentSize ) {// 长度小于等于限制直接打印
                    Log.println(priority, tag, log);
                }else {
                    //长度过长分页打印日志
                    long page =  (length-1)/segmentSize+1;//计算总页数
                    for (int i = 0 ;i<page;i++ ) {
                        long after = segmentSize*(i+1);
                        if(after>length){
                            after = length;
                        }
                        String logContent = log.substring(segmentSize*i,(int)after);
                         Log.println(priority, tag, logContent);
                    }
                }
            }
        } else {
            String logMessage = ex.getMessage();
            String logBody = Log.getStackTraceString(ex);
            log = String.format(LOG_FORMAT, logMessage, logBody);
            Log.println(priority, tag, log);
        }
    }

    public static boolean isDebug() {
        return isDebug;
    }

    public static void setDebug(boolean isDebug) {
        LogUtil.isDebug = isDebug;
    }

}
